package com.example.menuvirtualclient;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.RingtoneManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.menuvirtualclient.adapter.DishAdapter;
import com.example.menuvirtualclient.adapter.MenuAdapter;
import com.example.menuvirtualclient.adapter.OnSwipeTouchListener;
import com.example.menuvirtualclient.adapter.OrderAdapter;
import com.example.menuvirtualclient.core.Comment;
import com.example.menuvirtualclient.core.Dish;
import com.example.menuvirtualclient.core.DishComment;
import com.example.menuvirtualclient.core.DishMenu;
import com.example.menuvirtualclient.core.Menu;
import com.example.menuvirtualclient.core.Order;
import com.example.menuvirtualclient.core.OrderDetail;
import com.example.menuvirtualclient.core.Price;
import com.example.menuvirtualclient.core.Restaurant;
import com.example.menuvirtualclient.core.Table;
import com.example.menuvirtualclient.core.User;
import com.example.menuvirtualclient.presenter.MenuPresenter;
import com.example.menuvirtualclient.rule.CommentRule;
import com.example.menuvirtualclient.rule.DishRule;
import com.example.menuvirtualclient.util.Common;
import com.example.menuvirtualclient.util.MessageConsumer;
import com.example.menuvirtualclient.util.MessageConsumer.OnReceiveMessageHandler;
import com.example.menuvirtualclient.util.RestClient;
import com.example.menuvirtualclient.util.RestClient.RequestMethod;
import com.example.menuvirtualclient.util.SystemUiHider;
import com.example.menuvirtualclient.view.IView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class FullscreenActivity extends Activity implements IView {

	public static MenuPresenter _presenter;
	private GridView grdMenuList;
	private ListView listViewRight;
	private ListView listViewLeft;
	private ListView orderList;
	private ListView menuesList;
	public static int screenWidth;
	public static int screenHeight;
	public static int lateralPanelsWidth;
	public static boolean rightPanelOpen = false;
	public static boolean leftPanelOpen = false;
	public OrderAdapter orderAdapter;
	private ProgressDialog pDialog;
	public static Order _order;
	private static final String ORDER = "_order";
	public static AlertDialog dialog;
	public static int idDetail = 0;
	boolean isLeftListEnabled = true;
	boolean isRightListEnabled = true;
	public static LruCache<String, Bitmap> mMemoryCache;
	public static final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
	public static final int cacheSize = maxMemory / 8;
	public static int tempDetailId = 0;
	public static Context cnx;
	public static ImageButton btnRight;
	public static ImageButton btnLeft;
	ListView lstSecciones;
	ListView list_order;
	private MessageConsumer mConsumer;
	private String QUEUE_NAME = "MenuVirtual";
	public static NotificationManager notificationManager;
	
	
	
	public final int getIdDetail() {
		return idDetail;
	}

	public final void setIdDetail(int idDetail) {
		this.idDetail = idDetail;
	}

	int[] leftViewsHeights;
	int[] rightViewsHeights;
	boolean isOut = false;
	boolean isOrderOut = false;
	String mesa;
	Bitmap _bitMap;

	public static Table table;
	public static User waiter;
	public static Order order;
	private ProgressBar pb;

	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_fullscreen);
		// Guardo el contexto principal
		cnx = FullscreenActivity.this;

		// Obtengo las medidas de la pantallaa
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		screenWidth = metrics.widthPixels;
		screenHeight = metrics.heightPixels;
		// Dejo guardado el tama�o de los paneles laterales
		lateralPanelsWidth = Double
				.valueOf(screenWidth * Double.valueOf("0.8")).intValue();

		// Preparo el panel de �rdenes
		LinearLayout myRightPanel = (LinearLayout) findViewById(R.id.myRightPanel);
		myRightPanel.getLayoutParams().width = lateralPanelsWidth;
		myRightPanel.setTranslationX(screenWidth - convertDpToPixel(30, this));
		myRightPanel.setOnTouchListener(new OnSwipeTouchListener() {

		});

		// Preparo el panel de menu - left
		LinearLayout myLeftPanel = (LinearLayout) findViewById(R.id.myLeftPanel);
		myLeftPanel.getLayoutParams().width = lateralPanelsWidth;
		myLeftPanel.setTranslationX(-myLeftPanel.getLayoutParams().width
				+ convertDpToPixel(30, this));
		myLeftPanel.setOnTouchListener(new OnSwipeTouchListener() {

		});

		// Guardo los botones de los paneles en variables
		btnRight = (ImageButton) findViewById(R.id.btnOptionsRight);
		btnLeft = (ImageButton) findViewById(R.id.btnOptionsLeft);

		// Agrego el swipe a las secciones
		lstSecciones = (ListView) findViewById(R.id.lstSecciones);

		lstSecciones.setOnTouchListener(new OnSwipeTouchListener() {

		});

		// Agrego swipe a order
		list_order = (ListView) findViewById(R.id.list_order);

		list_order.setOnTouchListener(new OnSwipeTouchListener() {

		});

		ActionBar ab = getActionBar();
		ab.setDisplayShowHomeEnabled(false);
		ab.setDisplayShowTitleEnabled(false);
		ab.hide();

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mesa = extras
					.getString("com.example.menuvirtualclient.settingactivity");
		}

		mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				// The cache size will be measured in kilobytes rather than
				// number of items.
				return bitmap.getByteCount() / 1024;
			}
		};

		final View controlsView = findViewById(R.id.fullscreen_content_controls);

		final View contentView = findViewById(R.id.contentView);

		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS);
		mSystemUiHider.setup();

		Bundle b = new Bundle();
		b = getIntent().getExtras();

		if (b != null
				&& b.getBoolean("com.example.menuvirtualclient.update", false)) {

			updateSystem();

		} else {
			setMenusAdapter();
			setDishesAdapter(1);
		}

		if (_presenter.getFromTemp() != null) {
			_order = _presenter.getFromTemp();
		}

		// Create the consumer
		
		ExecuteConnectRabbit execute = new ExecuteConnectRabbit();
		// Connect to broker
		execute.execute("");
		
//		mConsumer = new MessageConsumer(Common.IP, "MenuVirtual", "fanout");
//		mConsumer.connectToRabbitMQ();

		// register for messages
//		mConsumer.setOnReceiveMessageHandler(new OnReceiveMessageHandler() {
//
//			public void onReceiveMessage(byte[] message) {
//				String text = "";
//				try {
//					text = new String(message, "UTF8");
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
//
//				AlertDialog alertDialog = new AlertDialog.Builder(
//						FullscreenActivity.this).create();
//
//				// Setting Dialog Title
//				alertDialog.setTitle(message.toString());
//
//				// Setting Dialog Message
//				alertDialog.setMessage(message.toString());
//
//				// Showing Alert Message
//				alertDialog.show();
//			}
//		});
	}

	/*
	 * M�todo para abrir y cerrar el panel derecho
	 */
	public void openRightPanel(View v) {
		// Use &lt; for <
		// Use &gt; for >
		// Use &amp; for &.

		// myOrderLateral.setTranslationX(screenWidth-
		// convertDpToPixel(((Button)findViewById(R.id.btnOpenSelector)).getWidth(),
		// this));

		LinearLayout ln = (LinearLayout) findViewById(R.id.myRightPanel);
		if (rightPanelOpen) {
			ln.animate().x(screenWidth - convertDpToPixel(30, this)).start();
			rightPanelOpen = false;
		} else {
			if (leftPanelOpen) {
				openLeftPanel(ln);
			} else {
				ln.animate().x(screenWidth - lateralPanelsWidth).start();
				if (_order != null) {
					GetOrderDetails(_order.getOrderDetails());

				}
				rightPanelOpen = true;
			}
		}
	}

	public void openLeftPanel(View v) {
		// Use &lt; for <
		// Use &gt; for >
		// Use &amp; for &.

		// myOrderLateral.setTranslationX(screenWidth-
		// convertDpToPixel(((Button)findViewById(R.id.btnOpenSelector)).getWidth(),
		// this));

		LinearLayout ln = (LinearLayout) findViewById(R.id.myLeftPanel);
		if (leftPanelOpen) {
			ln.animate()
					.x(-ln.getLayoutParams().width + convertDpToPixel(30, this))
					.start();
			leftPanelOpen = false;
		} else {

			if (rightPanelOpen) {
				openRightPanel(ln);
			} else {
				ln.animate().x(0).start();

				leftPanelOpen = true;
			}
		}
	}

	@Override
	public void onPause() {
		super.onPause(); // Always call the superclass method first

		// Release the Camera because we don't need it when paused
		// and other activities might need to use it.
		if (_order != null) {

		}
	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// Always call the superclass so it can restore the view hierarchy
		super.onRestoreInstanceState(savedInstanceState);

		// Restore state members from saved instance
		_order = Common.decodeOrder(savedInstanceState.getString(ORDER), this);
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		// Save the user's current game state
		if (_order != null) {
			savedInstanceState.putString(ORDER, Common.encodeOrder(_order));
		}
		// Always call the superclass so it can save the view hierarchy state
		super.onSaveInstanceState(savedInstanceState);
	}

	public void updateSystem() {
		pb = (ProgressBar) findViewById(R.id.progressBar1);
		// pb.setVisibility(View.GONE);

		pb.setVisibility(View.VISIBLE);

		_presenter = new MenuPresenter(this, pb);

		_presenter.deleteAllDishesMenues();
		_presenter.deleteAllMenues();
		_presenter.deleteAllDishes();
		_presenter.deleteAllPrices();

		// Cargo el listado de Menues
		WsMenuClient2 menuClient = new WsMenuClient2(getApplicationContext(),
				pb, _presenter);
		menuClient.execute(Common.URL_WS + "getMenusJson");

		pb.setVisibility(View.VISIBLE);
		// Cargo el listado de dishes
		WsDishClient2 dishClient = new WsDishClient2(getApplicationContext(),
				pb, _presenter);
		dishClient.execute(Common.URL_WS + "getAllDishesJson");

		pb.setVisibility(View.VISIBLE);
		// Cargo la relacion entre menues y dishes
		WsDishMenuClient2 dishMenuClient = new WsDishMenuClient2(
				getApplicationContext(), pb, _presenter);
		dishMenuClient.execute(Common.URL_WS + "getDishesMenuesJson");

		WsPricesClient pricesClient = new WsPricesClient(
				getApplicationContext(), _presenter);
		pricesClient.execute(Common.URL_WS + "getAllPricesJson");

		// Borro todo los datos de comments para evitar duplicados
		_presenter.deleteComments();

		pb.setVisibility(View.VISIBLE);
		// Cargo el listado de comments
		WsCommentClient2 commentClient = new WsCommentClient2(
				getApplicationContext(), pb, _presenter);
		commentClient.execute(Common.URL_WS + "getAllComments");

		pb.setVisibility(View.VISIBLE);
		// Cargo el listado de comments y la relacion con dishes
		WsDishCommentClient2 dishCommentClient = new WsDishCommentClient2(
				getApplicationContext(), pb, _presenter);
		dishCommentClient.execute(Common.URL_WS + "getAllDishesComments");

	}

	@Override
	public void LoadRestaurant(Restaurant restaurant) {
		TextView tvName = (TextView) findViewById(R.id.tvRestaurant);
		tvName.setText("Restaurante: " + restaurant.getName() + " - Tel�f: "
				+ restaurant.getPhone());
	}

	public void onGetServerClick(View button) {
		// ShowAlertDialog("Mesero",
		// "�Esta seguro que desea llamar al Mesero?",
		// "El Mesero ya fue notificado, en unos minutos estara con usted.");
		ShowToast("El Mesero ya fue notificado, en unos minutos estara con usted.");
		openRightPanel(findViewById(R.id.btnOptionsRight));
		// enviarOrder(button);
	}

	public void onGetCheckClick(View button) {
		// ShowAlertDialog("Cuenta",
		// "�Esta seguro que desea pedir la Cuenta?",
		// "La Cuenta ya fue emitida, en unos minutos sera llevada a su Mesa.");
		// ShowToast("Se pide la cuenta");
		// _presenter.ShowEnquiry();

		final Context innerContext = button.getContext();
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				button.getContext());

		// set title
		alertDialogBuilder.setTitle("Encuesta de calidad");

		// set dialog message
		alertDialogBuilder
				.setMessage(
						"�Desear�a completar una encuesta antes de retirarse?")
				.setCancelable(false)
				.setPositiveButton("Si", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// if this button is clicked, close
						// current activity
						Intent intent = new Intent(innerContext,
								EnquiryActivity.class);
						startActivity(intent);
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// if this button is clicked, just close
						// the dialog box and do nothing
						dialog.cancel();
					}
				});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void onGetMyOrderClick(View button) {

		// RelativeLayout llOrderList = (RelativeLayout)
		// findViewById(R.id.orderList);
		// llOrderList.setAnimationCacheEnabled(true);
		// llOrderList.setDrawingCacheEnabled(true);
		// View vBlackCourtain = (View) findViewById(R.id.blackCourtain);
		//
		// if (llOrderList.getVisibility() != View.VISIBLE) {
		// if (_order != null) {
		// GetOrderDetails(_order.getOrderDetails());
		//
		// }
		//
		// llOrderList.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		// vBlackCourtain.setVisibility(View.VISIBLE);
		// llOrderList.setVisibility(View.VISIBLE);
		// llOrderList.animate().alpha(1).start();
		// } else {
		// llOrderList.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		// llOrderList.animate().alpha(0).start();
		// llOrderList.setVisibility(View.GONE);
		// vBlackCourtain.setVisibility(View.GONE);
		// }

	}

	@SuppressWarnings("unused")
	private void ShowAlertDialog(String title, final String message,
			final String notify) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title);
		alert.setMessage(message);
		alert.setCancelable(false);
		alert.setPositiveButton("Confirmar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						ShowToast(notify);
					}
				});
		alert.setNegativeButton("Cancelar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		alert.show();
	}

	private void ShowToast(String message) {
		Toast toast = Toast.makeText(getApplicationContext(), message,
				Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	@Override
	public void SetMessage(String title, String message) {
		ShowToast(message);
	}

	@Override
	public Context GetContext() {
		return getApplicationContext();
	}

	public void showSelector(View view) {
		RelativeLayout llSelector = (RelativeLayout) findViewById(R.id.menuSelector);
		llSelector.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		llSelector.setAnimationCacheEnabled(true);
		llSelector.setDrawingCacheEnabled(true);
		View vBlackCourtain = (View) findViewById(R.id.blackCourtain);

		if (!isOrderOut) {
			llSelector.animate().x(0).start();
			vBlackCourtain.setVisibility(View.VISIBLE);
			if (_order != null) {
				((TextView) findViewById(R.id.selectorTableName)).setText(table
						.getName());
				((TextView) findViewById(R.id.selectorOrderNo)).setText(String
						.valueOf(_order.getId()));
				((TextView) findViewById(R.id.selectorWaiterName))
						.setText(waiter.getFirstName());
			}
			isOrderOut = true;
		} else {
			llSelector.animate().x(convertDpToPixel(-370, view.getContext()))
					.start();
			isOrderOut = false;
			vBlackCourtain.setVisibility(View.GONE);
		}
	}

	@Override
	public void LoadEntityList(List<Dish> dishes) {

		// listViewLeft = (ListView) findViewById(R.id.list_view_left);
		// listViewRight = (ListView) findViewById(R.id.list_view_right);
		//
		// int size = dishes.size();
		// int right = size / 2;
		// int left = size - right;
		// Dish[] dishLeft = new Dish[left];
		// Dish[] dishRight = new Dish[right];
		// int i = 0, j = 0;
		//
		// for (Dish dish : dishes) {
		// if (i < left) {
		// dishLeft[i] = dish;
		// } else {
		// dishRight[j] = dish;
		// j++;
		// }
		// i++;
		// }

		// DishAdapter menuAdapterRight = new DishAdapter(this,
		// R.layout.layout_menu_list_pint, dishRight);
		// DishAdapter menuAdapterLeft = new DishAdapter(this,
		// R.layout.layout_menu_list_pint, dishLeft);
		//
		// listViewLeft.setAdapter(menuAdapterLeft);
		// listViewRight.setAdapter(menuAdapterRight);
		//
		// listViewLeft.setOnTouchListener(touchListener);
		// listViewRight.setOnTouchListener(touchListener);
		// listViewLeft.setOnScrollListener(scrollListener);
		// listViewRight.setOnScrollListener(scrollListener);
		//
		// leftViewsHeights = new int[dishLeft.length];
		// rightViewsHeights = new int[dishRight.length];
	}

	// Passing the touch event to the opposite list
	OnTouchListener touchListener = new OnTouchListener() {
		boolean dispatched = false;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (v.equals(listViewLeft) && !dispatched) {
				dispatched = true;
				listViewRight.dispatchTouchEvent(event);
			} else if (v.equals(listViewRight) && !dispatched) {
				dispatched = true;
				listViewLeft.dispatchTouchEvent(event);
			}

			dispatched = false;
			return false;
		}
	};

	/**
	 * Synchronizing scrolling Distance from the top of the first visible
	 * element opposite list: sum_heights(opposite invisible screens) -
	 * sum_heights(invisible screens) + distance from top of the first visible
	 * child
	 */
	OnScrollListener scrollListener = new OnScrollListener() {

		int currentVisibleItemCount;
		int currentScrollState;
		int currentFirstVisibleItem;

		private void isScrollCompleted(AbsListView view) {
			// if (this.currentVisibleItemCount > 0 && this.currentScrollState
			// == SCROLL_STATE_IDLE) {
			if (this.currentVisibleItemCount > 0
					&& this.currentScrollState == SCROLL_STATE_FLING) {
				if (view.getChildAt(0) != null) {
					if (view.equals(listViewLeft)) {
						leftViewsHeights[view.getFirstVisiblePosition()] = view
								.getChildAt(0).getHeight();

						int h = 0;
						for (int i = 0; i < listViewRight
								.getFirstVisiblePosition(); i++) {
							h += rightViewsHeights[i];
						}

						int hi = 0;
						for (int i = 0; i < listViewLeft
								.getFirstVisiblePosition(); i++) {
							hi += leftViewsHeights[i];
						}

						int top = h - hi + view.getChildAt(0).getTop();
						listViewRight.setSelectionFromTop(
								listViewRight.getFirstVisiblePosition(), top);
					} else if (view.equals(listViewRight)) {
						rightViewsHeights[view.getFirstVisiblePosition()] = view
								.getChildAt(0).getHeight();

						int h = 0;
						for (int i = 0; i < listViewLeft
								.getFirstVisiblePosition(); i++) {
							h += leftViewsHeights[i];
						}

						int hi = 0;
						for (int i = 0; i < listViewRight
								.getFirstVisiblePosition(); i++) {
							hi += rightViewsHeights[i];
						}

						int top = h - hi + view.getChildAt(0).getTop();
						listViewLeft.setSelectionFromTop(
								listViewLeft.getFirstVisiblePosition(), top);
					}

				}
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView v, int scrollState) {
			this.currentScrollState = scrollState;
			this.isScrollCompleted(v);

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			this.currentFirstVisibleItem = firstVisibleItem;
			this.currentVisibleItemCount = visibleItemCount;

		}
	};

	@Override
	public void GetOrder(String table, Restaurant restaurant) {
		TextView tvName = (TextView) findViewById(R.id.tvRestaurant);
		TextView tvDate = (TextView) findViewById(R.id.tvDate);
		TextView tvTable = (TextView) findViewById(R.id.tvTable);

		tvName.setText("Restaurante: " + restaurant.getName() + " - Tel�f: "
				+ restaurant.getPhone());
		tvDate.setText("12/04/2013");
		tvTable.setText("004");
	}

	public void onClickPopUpLogin(View v) {
		Button btn = (Button) v;
		EditText ed = (EditText) ((LinearLayout) v.getParent().getParent())
				.findViewById(R.id.txtLoginPass);
		ed.setText(ed.getText().toString() + btn.getTag());
	}

	public void onClickClear(View v) {
		EditText ed = (EditText) ((LinearLayout) v.getParent().getParent())
				.findViewById(R.id.txtLoginPass);
		ed.setText("");
	}

	/**
	 * EN ESTE METODO SE REALIZA EL LOGUEO DEL USUARIO.
	 * 
	 * @param view
	 */
	public void goToSettings(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = this.getLayoutInflater();
		builder.setView(inflater.inflate(R.layout.layout_settings_login, null));
		dialog = builder.create();

		dialog.show();

		LinearLayout ln = (LinearLayout) dialog
				.findViewById(R.id.popupSettignsLogin);
		Button btnOk = (Button) ln.findViewById(R.id.btnLoginOk);
		btnOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				EditText ed = (EditText) ((LinearLayout) v.getParent()
						.getParent()).findViewById(R.id.txtLoginPass);
				TextView edUserName = (TextView) ((LinearLayout) v.getParent()
						.getParent().getParent().getParent())
						.findViewById(R.id.txtUserNameLogin);
				Editable value = ed.getText();
				if (edUserName.getText().toString().equals("")) {
					ShowToast("Debe seleccionar un usaurio");
					return;
				}

				if (value.toString().equals("")) {
					ShowToast("Debe ingresar su password");
					return;
				}
				_presenter.Login(edUserName.getText().toString(),
						value.toString());
				waiter = _presenter.getUser();
				dialog.cancel();
			}
		});
		Button btnCancel = (Button) ln.findViewById(R.id.btnLoginCancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				dialog.cancel();
			}
		});

		ListView lvUsers = (ListView) ln.findViewById(R.id.lstUsersLogin);

		List<User> users = _presenter.getAllUsers();
		List<String> usersStr = new ArrayList<String>();

		for (User usr : users) {
			usersStr.add(usr.toString());
		}

		String[] usersStrLst = new String[usersStr.size()];
		usersStr.toArray(usersStrLst);

		// ArrayAdapter<String> listArrayAdapter = new
		// ArrayAdapter<String>(this,
		// R.layout.layout_users_list, usersStrLst);

		ArrayAdapter<String> listArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.layout_users_list, R.id.tvUser, usersStrLst);

		lvUsers.setAdapter(listArrayAdapter);

	}

	public void setUser(View v) {

		TextView edUserName = (TextView) ((LinearLayout) v.getParent()
				.getParent().getParent()).findViewById(R.id.txtUserNameLogin);

		edUserName.setText(((TextView) v).getText().toString());

	}

	public static float convertPixelsToDp(float px, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float dp = px / (metrics.densityDpi / 160f);
		return dp;
	}

	public static float convertDpToPixel(float dp, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	public void closeDetail(View v) {
		RelativeLayout rlDishDetail = (RelativeLayout) findViewById(R.id.dishDetail);

		View vBlackCourtain = (View) findViewById(R.id.blackCourtain);

		rlDishDetail.animate().alpha(0).start();
		rlDishDetail.setVisibility(View.GONE);

		vBlackCourtain.setVisibility(View.GONE);
	}

	@Override
	public void ShowEnquiry() {
		Intent intent = new Intent(FullscreenActivity.this,
				EnquiryActivity.class);
		startActivity(intent);
	}

	@Override
	public void navigate(Class<?> destination) {
		Intent navigation = new Intent(this, destination);
		this.startActivity(navigation);
	}

	@Override
	public void navigate(Class<?> destination, boolean logoutFlag) {
		// TODO Auto-generated method stub

	}

	@Override
	public void navigate(Class<?> destination, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showError(String errorMessage) {
		// TODO Auto-generated method stub

	}

	// Ejemplo de tarea asincr�nica e invocaci�n del servicio

	private class MiTarea extends AsyncTask<String, String, String> {
		RestClient client;

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected String doInBackground(String... urls) {

			// http://localhost:1313/menuvirtualws/services/OperatorClass/saveDishToOrder?idDish=0&idOrder=0&idTable=0&idWaiter=0&time=1240&comments=hola
			client = new RestClient(urls[0]);

			client.AddParam("orderDetails", urls[1]);
			try {
				client.Execute(RequestMethod.GET);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String response = client.getResponse();
			publishProgress(response);
			return response;
		}

		protected void onProgressUpdate(String... valores) {
			// ((TextView)findViewById(R.id.texto)).setText(valores[0].toString());

			ShowToast("Enviando Order");
		}

		protected void onPostExecute(String bytes) {
			ShowToast("Order Enviada, Muchas gracias.");
			updateOrderStatus();
		}
	}

	// Agrega el plato desde el menu emergente
	public void addDishI(View v) {

		OrderDetail orderDetail = new OrderDetail();
		RelativeLayout rlDishDetail = (RelativeLayout) ((View) v.getParent()
				.getParent().getParent()).findViewById(R.id.dishDetail);
		int dishId = Integer.parseInt(((TextView) rlDishDetail
				.findViewById(R.id.idMenu2)).getText().toString());

		Order order = new Order();
		Dish dish = new Dish();
		try {
			order = _order;
			dish = _presenter.getDish(dishId);

			// Verifico que tamaño y precio están seleccionados
			RadioGroup rdoGroup = (RadioGroup) ((View) v.getParent())
					.findViewById(R.id.llBtnPrice);

			int count = rdoGroup.getChildCount();
			String size = "Normal";
			for (int i = 0; i < count; i++) {
				View o = rdoGroup.getChildAt(i);
				if (o instanceof RadioButton && ((RadioButton) o).isChecked()) {
					size = ((RadioButton) o).getText().toString().split(" ")[0];
					size = (size.equals("")) ? "Normal" : size;
					dish.setPrice(Double.valueOf(((RadioButton) o).getText()
							.toString().split(" ")[1].replace("$", "")));
				}
			}

			dish.setSize(size);

		} catch (Exception e1) {
			e1.printStackTrace();
		}

		orderDetail.setDish(dish);
		orderDetail.setStatus(-1);
		orderDetail.setOrder(order);

		_order.getOrderDetails().add(orderDetail);
		rlDishDetail.findViewById(R.id.btnCloseDetail).performClick();
		new AddComments(v, orderDetail, 0);

		// onAddCommentClick((View)v.getParent());
	}

	public void enviarOrder(View view) {

		if (_order == null)
			return;

		String order = Common.encodeOrderActive(_order);

		// for (OrderDetail od : _order.getOrderDetails()) {
		// od.setStatus(1);
		// }

		if (order.split("\\[").length > 1) {
			new MiTarea().execute(Common.URL_WS + "saveDishesToOrder",
					order.toString());
		}
		_presenter.saveToTemp(_order);
		tempDetailId = 0;

		openRightPanel(findViewById(R.id.btnOptionsRight));

	}

	// Actualizo el estado de la orden en memoria para que quede el mismo estado
	// que en el server, enviado = 1
	public void updateOrderStatus() {
		for (OrderDetail od : _order.getOrderDetails()) {
			od.setStatus(1);

		}
		_presenter.saveToTemp(_order);
	}

	@Override
	public void CloseView(View v) {
		RelativeLayout rlDishDetail = (RelativeLayout) ((View) v.getParent()
				.getParent().getParent()).findViewById(R.id.dishDetail);
		rlDishDetail.setVisibility(v.GONE);
		rlDishDetail.animate().alpha(0);
	}

	public void onRemoveMenuToOrderClick(View v) {
		TextView tvIdDetail = (TextView) ((RelativeLayout) v.getParent())
				.findViewById(R.id.idMenu);
		int idDetail = Integer.valueOf(tvIdDetail.getText().toString());
		for (OrderDetail detail : _order.getOrderDetails()) {
			if (detail.getStatus() == -1 && detail.getId() == idDetail) {
				_order.getOrderDetails().remove(detail);
				break;
			}
		}

		GetOrderDetails(_order.getOrderDetails());

	}

	@Override
	public void LoadMainMenu(Menu[] menues) {
		// menuesList = (ListView) findViewById(R.id.lstSecciones);
		// final MenuAdapter menuAdapter = new MenuAdapter(this,
		// R.layout.layout_secciones_list, menues, _presenter);
		// menuesList.setAdapter(menuAdapter);
	}

	@Override
	public void ShowTables() {
		Intent myIntent = new Intent(FullscreenActivity.this,
				SettingsActivity.class);
		startActivity(myIntent);
		if (table != null) {
			Log.i("TableID", Integer.toString(table.getId()));

		}
	}

	@Override
	public void GetOrderDetails(List<OrderDetail> orderDetails) {
		// orderDetailsList = orderDetails;
		orderList = (ListView) findViewById(R.id.list_order);
		orderAdapter = new OrderAdapter(this, R.layout.layout_order_list,
				orderDetails.toArray(new OrderDetail[orderDetails.size()]));
		orderList.setAdapter(orderAdapter);

	}

	private class WsMenuClient2 extends AsyncTask<String, Integer, String> {

		private RestClient client;
		private String request;
		private List<Menu> menus;
		private MenuPresenter presenter;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsMenuClient2(Context context, ProgressBar pb,
				MenuPresenter presenter) {
			this.mContext = context;
			this.pb = pb;
			this.presenter = presenter;
		}

		public List<Menu> getMenus() {
			return menus;
		}

		public String getRequest() {
			return request;
		}

		protected void onPreExecute() {

		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getMenusJsonResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace("</ns:return></ns:getMenusJsonResponse>", "");
				Gson gson = new Gson();
				List<Menu> list = gson.fromJson(response,
						new TypeToken<List<Menu>>() {
						}.getType());
				if (list != null && list.size() > 0) {
					menus = list;
					response = "Ok";
					for (Menu menu : menus) {
						Menu entity = presenter.getMenu(menu.getId());
						if (entity != null) {
							if (!entity.equals(menu)) {
								presenter.Update(menu);
							}
						} else {
							presenter.Insert(menu);
						}
					}
					// presenter.LoadMainMenu();
				} else {
					Log.i("WsMenuClient", "null");
					error = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}
			// pb.setVisibility(View.GONE);
			publishProgress(100);
			return response;
		}

		protected void onProgressUpdate(Integer... progress) {
			pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {

			setMenusAdapter();
		}

	}

	// Servicio para precios
	private class WsPricesClient extends AsyncTask<String, Integer, String> {

		RestClient client;
		private String request;
		private List<Price> prices;
		private DishRule _rule;
		private MenuPresenter presenter;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsPricesClient(Context context, MenuPresenter presenter) {
			this.mContext = context;
			this.presenter = presenter;
		}

		public List<Price> getPrices() {
			return prices;
		}

		public String getRequest() {
			return request;
		}

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected void onProgressUpdate(Integer... progress) {
			// pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {
			// pb.setVisibility(View.GONE);

		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getAllPricesJsonResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace("</ns:return></ns:getAllPricesJsonResponse>",
								"");
				Gson gson = new Gson();
				List<Price> list = gson.fromJson(response,
						new TypeToken<List<Price>>() {
						}.getType());
				if (list != null) {
					prices = list;
					response = "Ok";
					// presenter.deletePrice(prices);
					// for (Price price : prices) {
					presenter.savePrice(prices);
					// }
					// for (Dish dish : dishes) {
					// Dish entity = presenter.getDish(dish.getId());
					// if (entity != null) {
					// if (!entity.equals(dish)) {
					// presenter.Update(dish);
					// }
					// } else {
					// presenter.Insert(dish);
					// }
					// }
					// presenter.LoadDishes(1);
				} else {
					Log.i("WsPriceClient", "null");
				}

			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}

			publishProgress(100);
			return response;
		}

	}

	private class WsDishClient2 extends AsyncTask<String, Integer, String> {

		RestClient client;
		private String request;
		private List<Dish> dishes;
		private DishRule _rule;
		private MenuPresenter presenter;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsDishClient2(Context context, ProgressBar pb,
				MenuPresenter presenter) {
			this.mContext = context;
			this.pb = pb;
			this.presenter = presenter;
		}

		public List<Dish> getDishes() {
			return dishes;
		}

		public String getRequest() {
			return request;
		}

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected void onProgressUpdate(Integer... progress) {
			pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {
			pb.setVisibility(View.GONE);

		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getAllDishesJsonResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace("</ns:return></ns:getAllDishesJsonResponse>",
								"");
				Gson gson = new Gson();
				List<Dish> list = gson.fromJson(response,
						new TypeToken<List<Dish>>() {
						}.getType());
				if (list != null) {
					dishes = list;
					response = "Ok";
					presenter.deleteAllDishes();
					for (Dish dish : dishes) {
						presenter.Insert(dish);
					}
					// for (Dish dish : dishes) {
					// Dish entity = presenter.getDish(dish.getId());
					// if (entity != null) {
					// if (!entity.equals(dish)) {
					// presenter.Update(dish);
					// }
					// } else {
					// presenter.Insert(dish);
					// }
					// }
					// presenter.LoadDishes(1);
				} else {
					Log.i("WsDishClient", "null");
				}

			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}

			publishProgress(100);
			return response;
		}

	}

	private class WsDishMenuClient2 extends AsyncTask<String, Integer, String> {

		RestClient client;
		private String request;
		private MenuPresenter presenter;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsDishMenuClient2(Context context, ProgressBar pb,
				MenuPresenter presenter) {
			this.mContext = context;
			this.pb = pb;
			this.presenter = presenter;
		}

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected void onProgressUpdate(Integer... progress) {
			pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {

			WsCommentClient2 dishMenuClient = new WsCommentClient2(
					getApplicationContext(), pb, _presenter);
			dishMenuClient.execute(Common.URL_WS + "getAllComments");
			// presenter.LoadDishes(1);

		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getDishesMenuesJsonResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace(
								"</ns:return></ns:getDishesMenuesJsonResponse>",
								"");
				Gson gson = new Gson();
				List<DishMenu> list = gson.fromJson(response,
						new TypeToken<List<DishMenu>>() {
						}.getType());
				if (list != null) {
					for (DishMenu dishMenu : list) {
						boolean exist = presenter.exist(dishMenu);
						if (!exist) {
							presenter.Insert(dishMenu);
						}
					}
					response = "Ok";

				} else {
					Log.i("WsDishClient", "null");
				}

			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}

			publishProgress(100);
			return response;
		}
	}

	private void setMenusAdapter() {
		pb = (ProgressBar) findViewById(R.id.progressBar1);
		pb.setVisibility(View.VISIBLE);
		_presenter = new MenuPresenter(this, pb);
		pb.setVisibility(View.GONE);

		List<Menu> menues = _presenter.getAllMenu();
		// Menu[] menues = menus.toArray(new Menu[menus.size()]);
		menuesList = (ListView) findViewById(R.id.lstSecciones);
		final MenuAdapter menuAdapter = new MenuAdapter(
				FullscreenActivity.this, R.layout.layout_secciones_list,
				menues, _presenter);
		menuesList.setAdapter(menuAdapter);
	}

	@Override
	public void LoadEntityList(int menuId) {
		setDishesAdapter(menuId);
	}

	public static void openPanel(String side) {
		if (side.equals("l")) {
			btnRight.performClick();
		} else {
			btnLeft.performClick();
		}
	}

	public void setDishesAdapter(int idMenu) {
		// pb.setVisibility(View.GONE);
		pb = (ProgressBar) findViewById(R.id.progressBar1);
		pb.setVisibility(View.VISIBLE);
		_presenter = new MenuPresenter(this, pb);
		pb.setVisibility(View.GONE);

		List<Dish> dishes = _presenter.GetDishesByMenu(idMenu);

		listViewLeft = (ListView) findViewById(R.id.list_view_left);

		listViewLeft.setOnTouchListener(new OnSwipeTouchListener() {

		});

		// listViewRight = (ListView) findViewById(R.id.list_view_right);

		// int fullListSize = 0;
		// for (Dish dish : dishes) {
		// if (dish.getPhoto().equals("")) {
		// fullListSize = fullListSize+150;
		// } else {
		// fullListSize = fullListSize+360;
		// }
		// }
		//
		// int halfListSize = fullListSize / 2;
		// int listRightSize = 0;
		// int listLeftSize = 0;
		//
		// List<Dish> dishLeft = new ArrayList<Dish>();
		// List<Dish> dishRight= new ArrayList<Dish>();
		//
		// for (Dish dish : dishes) {
		//
		// if (listLeftSize <= halfListSize){
		// dishLeft.add(dish);
		// if(dish.getPhoto().equals("")){
		// listLeftSize =listLeftSize+ 150;
		// }else{
		// listLeftSize =listLeftSize+ 400;
		// }
		// }else{
		// dishRight.add(dish);
		// }
		//
		//
		// }
		//
		// int size = dishes.size();
		// int right = size / 2;
		// int left = size - right;
		// Dish[] dishLeft = new Dish[left];
		// Dish[] dishRight = new Dish[right];
		// int i = 0, j = 0;
		//
		// for (Dish dish : dishes) {
		// if (i < left) {
		// dishLeft[i] = dish;
		// } else {
		// dishRight[j] = dish;
		// j++;
		// }
		// i++;
		// }

		// DishAdapter menuAdapterRight = new
		// DishAdapter(FullscreenActivity.this,
		// R.layout.layout_menu_list_pint, dishRight);
		DishAdapter menuAdapterLeft = new DishAdapter(FullscreenActivity.this,
				R.layout.layout_dishes_list, dishes);

		listViewLeft.setAdapter(menuAdapterLeft);
		// listViewRight.setAdapter(menuAdapterRight);
		//
		// listViewLeft.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
		// listViewRight.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
		//
		// listViewLeft.setOnScrollListener(new OnScrollListener() {
		//
		// @Override
		// public void onScrollStateChanged(AbsListView view, int scrollState) {
		// // onScroll will be called and there will be an infinite loop.
		// // That's why i set a boolean value
		// if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
		// isRightListEnabled = false;
		// } else if (scrollState == SCROLL_STATE_IDLE) {
		// isRightListEnabled = true;
		// }
		// }
		//
		// @Override
		// public void onScroll(AbsListView view, int firstVisibleItem,
		// int visibleItemCount, int totalItemCount) {
		// View c = view.getChildAt(0);
		// if (c != null && isLeftListEnabled) {
		// listViewRight.setSelectionFromTop(firstVisibleItem,
		// c.getTop());
		// }
		// }
		// });
		//
		// listViewRight.setOnScrollListener(new OnScrollListener() {
		// @Override
		// public void onScrollStateChanged(AbsListView view, int scrollState) {
		// if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
		// isLeftListEnabled = false;
		// } else if (scrollState == SCROLL_STATE_IDLE) {
		// isLeftListEnabled = true;
		// }
		// }
		//
		// @Override
		// public void onScroll(AbsListView view, int firstVisibleItem,
		// int visibleItemCount, int totalItemCount) {
		// View c = view.getChildAt(0);
		// if (c != null && isRightListEnabled) {
		// listViewLeft.setSelectionFromTop(firstVisibleItem,
		// c.getTop());
		// }
		// }
		// });

		// listViewLeft.setOnTouchListener(touchListener);
		// listViewRight.setOnTouchListener(touchListener);
		// listViewLeft.setOnScrollListener(scrollListener);
		// listViewRight.setOnScrollListener(scrollListener);
		//
		// leftViewsHeights = new int[dishLeft.length];
		// rightViewsHeights = new int[dishRight.length];
	}

	public void onAddCommentClick(View view) {

		OrderDetail orderDetail = new OrderDetail();
		TextView tvIdDish = (TextView) ((RelativeLayout) view.getParent())
				.findViewById(R.id.idDish);
		orderDetail.getDish().setId(
				Integer.valueOf(tvIdDish.getText().toString()));

		TextView tvIdDetail = (TextView) ((RelativeLayout) view.getParent())
				.findViewById(R.id.idMenu);
		orderDetail.setId(Integer.valueOf(tvIdDetail.getText().toString()));

		new AddComments(view, orderDetail, 1);

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// LayoutInflater inflater = this.getLayoutInflater();
		// final List<Integer> intList = new ArrayList<Integer>();
		// final int dishId;
		// final int detailId;
		//
		// builder.setView(inflater.inflate(R.layout.layout_order_comments,
		// null));
		// dialog = builder.create();
		//
		// dialog.show();
		//
		// final TextView tvCommentsList = (TextView) ((RelativeLayout) view
		// .getParent()).findViewById(R.id.commentsList);
		//
		// LinearLayout ln = (LinearLayout) dialog
		// .findViewById(R.id.listCommentsDialog);
		//
		// LinearLayout lh = new LinearLayout(view.getContext());
		// lh.setOrientation(0);
		// Button btnCancelar = new Button(this);
		// btnCancelar.setText("Cancelar");
		// btnCancelar.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// dialog.dismiss();
		// }
		// });
		//
		// Button btnAceptar = new Button(this);
		// btnAceptar.setText("Aceptar");
		// btnAceptar.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// List<Comment> cos = new ArrayList<Comment>();
		// CommentRule _commentRule = new CommentRule(v.getContext());
		// tvCommentsList.setText("");
		// for (int id : intList) {
		// Comment co = new Comment();
		// // co.setId(id);
		// // cos.add(co);
		// try {
		// co = _commentRule.Get(id);
		// cos.add(co);
		// tvCommentsList.setText(tvCommentsList.getText()
		// .toString() + " " + co.getDescription());
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// }
		//
		// for (OrderDetail od : _order.getOrderDetails()) {
		// if (od.getId() == getIdDetail()) {
		// od.setComments(cos);
		// }
		// }
		//
		// // Salvo el estado de la orden
		// _presenter.saveToTemp(FullscreenActivity._order);
		//
		// intList.clear();
		// dialog.cancel();
		// }
		// });
		//
		// TextView tvIdDish = (TextView) ((RelativeLayout) view.getParent())
		// .findViewById(R.id.idDish);
		// dishId = Integer.valueOf(tvIdDish.getText().toString());
		// TextView tvIdDetail = (TextView) ((RelativeLayout) view.getParent())
		// .findViewById(R.id.idMenu);
		// setIdDetail(Integer.valueOf(tvIdDetail.getText().toString()));
		// // Busco el comment list del plato para despu�s actualizar el
		// detalle
		//
		// List<OrderDetail> lstDetails = _order.getOrderDetails();
		//
		// List<Comment> lstComments = _presenter.GetCommentByDish(dishId);
		//
		// for (Comment comment : lstComments) {
		// CheckBox ch = new CheckBox(this);
		// for (OrderDetail od : lstDetails) {
		// if (od.getComments() != null && od.getId() == getIdDetail()) {
		// for (Comment c : od.getComments()) {
		// if (c != null && comment.getId() == c.getId()) {
		// ch.setChecked(true);
		// intList.add(c.getId());
		// //
		// tvCommentsList.setText(tvCommentsList.getText().toString()+c.getDescription());
		// }
		// }
		// }
		// }
		// ch.setOnCheckedChangeListener(new
		// CompoundButton.OnCheckedChangeListener() {
		//
		// @Override
		// public void onCheckedChanged(CompoundButton buttonView,
		// boolean isChecked) {
		// // TODO Auto-generated method stub
		// Log.i("onCheckedChanged", "=========================");
		// Log.i("buttonView.getId()",
		// Integer.toString(buttonView.getId()));
		// if (isChecked) {
		// intList.add(buttonView.getId());
		// } else {
		// // C�digo original - Error: Indice fuera de rango
		// // Invalid index 2, size is 2
		// // intList.remove(buttonView.getId());
		// // ----------------------------------------
		// for (int i = 0; i < intList.size(); i++)
		// if (intList.get(i) == buttonView.getId()) {
		// intList.remove(i);
		// }
		// }
		// }
		// });
		//
		// ch.setTextAppearance(this, R.style.AppTitlesPopUp);
		// ch.setText(comment.getDescription());
		// ch.setId(comment.getId());
		// ln.addView(ch);
		// }
		// lh.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.WRAP_CONTENT));
		// lh.setWeightSum(2);
		//
		// LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) lh
		// .getLayoutParams(); // or create new LayoutParams...
		//
		// lParams.weight = 1f;
		//
		// btnAceptar.setLayoutParams(lParams);
		// btnCancelar.setLayoutParams(lParams);
		//
		// lh.addView(btnAceptar);
		// lh.addView(btnCancelar);
		//
		// ln.addView(lh);
	}

	private class WsDishCommentClient2 extends
			AsyncTask<String, Integer, String> {

		RestClient client;
		private String request;
		private MenuPresenter presenter;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsDishCommentClient2(Context context, ProgressBar pb,
				MenuPresenter presenter) {
			this.mContext = context;
			this.pb = pb;
			this.presenter = presenter;
		}

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected void onProgressUpdate(Integer... progress) {
			pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {
			pb.setVisibility(View.GONE);
			Log.i("Info", "Fin del thread WsDishCommentClient2...");
			setDishesAdapter(1);
		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getAllDishesCommentsResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace(
								"</ns:return></ns:getAllDishesCommentsResponse>",
								"");
				if (response != null) {
					// Hacer el split y cargar el Comment
					String[] arrComment = response.substring(0,
							response.length() - 1).split(";");

					List<DishComment> dishComments = new ArrayList<DishComment>();

					for (String s : arrComment) {
						DishComment dishComment = new DishComment();
						dishComment.setDishId(Integer.valueOf(s.split(",")[0]));
						dishComment
								.setCommentId(Integer.valueOf(s.split(",")[1]));

						dishComments.add(dishComment);
					}

					response = "Ok";
					presenter.SaveDishComments(dishComments);

				} else {
					Log.i("WsDishCommentClient2", "null");
				}
			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}

			publishProgress(100);
			return response;
		}
	}

	private class WsCommentClient2 extends AsyncTask<String, Integer, String> {

		RestClient client;
		private String request;
		private MenuPresenter presenter;
		private List<Comment> comments;

		private boolean error = false;
		private Context mContext;
		private ProgressBar pb;

		public WsCommentClient2(Context context, ProgressBar pb,
				MenuPresenter presenter) {
			this.mContext = context;
			this.pb = pb;
			this.presenter = presenter;
			comments = new ArrayList<Comment>();
		}

		protected void onPreExecute() {
			// Mostramos el di�logo antes de comenzar
		}

		protected void onProgressUpdate(Integer... progress) {
			pb.setProgress(progress[0]);
			Log.i("Info", "Procesando...");
		}

		protected void onPostExecute(String content) {
			pb.setVisibility(View.GONE);
			Log.i("Info", "Fin del thread WsCommentClient2...");

		}

		@Override
		protected String doInBackground(String... params) {
			client = new RestClient(params[0]);
			String response = "Error";

			try {
				client.Execute(RequestMethod.GET);
				response = client
						.getResponse()
						.replace(
								"<ns:getAllCommentsResponse xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>",
								"")
						.replace("</ns:return></ns:getAllCommentsResponse>", "");
				if (response != null) {
					// Hacer el split y cargar el Comment

					String[] arrComment = response.substring(0,
							response.length() - 1).split(";");

					List<Comment> comments = new ArrayList<Comment>();

					for (String comment : arrComment) {
						Comment cmt = new Comment();
						cmt.setId(Integer.valueOf(comment.split(",")[0]));
						cmt.setDescription(comment.split(",")[1]);
						cmt.setPrice(Double.valueOf(comment.split(",")[2]));

						comments.add(cmt);
					}

					response = "Ok";
					presenter.SaveComments(comments);
				} else {
					Log.i("WsCommentClient2", "null");
				}
			} catch (Exception e) {
				e.printStackTrace();
				error = true;
				cancel(true);
			}

			publishProgress(100);
			return response;
		}
	}

	public class AddComments extends Activity {

		public AddComments(View view, OrderDetail orderDetail, int check) {
			addComments(view, orderDetail, check);
		}

		public void addComments(View view, OrderDetail orderDetail, int check) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					view.getContext());
			LayoutInflater inflater = (LayoutInflater) view.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final List<Integer> intList = new ArrayList<Integer>();
			final int dishId;
			final int detailId;

			builder.setView(inflater.inflate(R.layout.layout_order_comments,
					null));
			FullscreenActivity.dialog = builder.create();

			FullscreenActivity.dialog.show();

			// final TextView tvCommentsList = (TextView) ((RelativeLayout) view
			// .getParent()).findViewById(R.id.commentsList);

			LinearLayout ln = (LinearLayout) FullscreenActivity.dialog
					.findViewById(R.id.listCommentsDialog);
			final EditText etComment = (EditText) ln
					.findViewById(R.id.etComment);

			LinearLayout lh = new LinearLayout(view.getContext());
			lh.setOrientation(0);
			Button btnCancelar = new Button(view.getContext());
			btnCancelar.setText("Cancelar");
			btnCancelar.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					FullscreenActivity.dialog.dismiss();
				}
			});

			// Agrego los tipos de plato - entra principal o postres
			RadioGroup rgrDetailTypes = new RadioGroup(view.getContext());
			rgrDetailTypes.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			rgrDetailTypes.setOrientation(0);

			final RadioButton rdoStarter = new RadioButton(view.getContext());
			rdoStarter.setText("Entrada");
			rdoStarter.setTextColor(view.getContext().getResources()
					.getColor(R.color.AlmostBlack));
			rdoStarter.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoStarter.setTypeface(Typeface.create("sans-serif-light",
					Typeface.NORMAL));
			rdoStarter.setTextSize(20);

			final RadioButton rdoMain = new RadioButton(view.getContext());
			rdoMain.setText("P. Principal");
			rdoMain.setTextColor(view.getContext().getResources()
					.getColor(R.color.AlmostBlack));
			rdoMain.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoMain.setTypeface(Typeface.create("sans-serif-light",
					Typeface.NORMAL));
			rdoMain.setTextSize(20);

			final RadioButton rdoDessert = new RadioButton(view.getContext());
			rdoDessert.setText("Postre");
			rdoDessert.setTextColor(view.getContext().getResources()
					.getColor(R.color.AlmostBlack));
			rdoDessert.setButtonDrawable(R.drawable.btn_radio_holo_light);
			rdoDessert.setTypeface(Typeface.create("sans-serif-light",
					Typeface.NORMAL));
			rdoDessert.setTextSize(20);

			rgrDetailTypes.addView(rdoDessert);
			rgrDetailTypes.addView(rdoMain);
			rgrDetailTypes.addView(rdoStarter);

			Button btnAceptar = new Button(view.getContext());
			btnAceptar.setText("Aceptar");
			btnAceptar.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					List<Comment> cos = new ArrayList<Comment>();
					CommentRule _commentRule = new CommentRule(v.getContext());
					// tvCommentsList.setText("");
					for (int id : intList) {
						Comment co = new Comment();
						// co.setId(id);
						// cos.add(co);
						try {
							co = _commentRule.Get(id);
							cos.add(co);
							// tvCommentsList.setText(tvCommentsList.getText()
							// .toString() + " " + co.getDescription());

						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					for (OrderDetail od : FullscreenActivity._order
							.getOrderDetails()) {
						if (od.getId() == FullscreenActivity.idDetail) {
							od.setComments(cos);
							od.setComment(etComment.getText().toString());
							if (rdoDessert.isChecked())
								od.setDetail_type(2);
							if (rdoMain.isChecked())
								od.setDetail_type(1);
							if (rdoStarter.isChecked())
								od.setDetail_type(0);
						}
					}

					// Salvo el estado de la orden
					FullscreenActivity._presenter
							.saveToTemp(FullscreenActivity._order);

					intList.clear();
					FullscreenActivity.dialog.cancel();
				}
			});

			// TextView tvIdDish = (TextView) ((RelativeLayout)
			// view.getParent())
			// .findViewById(R.id.idDish);
			// dishId = Integer.valueOf(tvIdDish.getText().toString());
			// TextView tvIdDetail = (TextView) ((RelativeLayout)
			// view.getParent())
			// .findViewById(R.id.idMenu);

			dishId = orderDetail.getDish().getId();

			FullscreenActivity.idDetail = Integer.valueOf(orderDetail.getId());
			// Busco el comment list del plato para despu�s actualizar el
			// detalle

			List<OrderDetail> lstDetails = FullscreenActivity._order
					.getOrderDetails();

			List<Comment> lstComments = FullscreenActivity._presenter
					.GetCommentByDish(dishId);

			ln.addView(rgrDetailTypes);
			if (orderDetail.getDish().getType() == 0) {
				rdoMain.setChecked(true);
			} else if (orderDetail.getDish().getType() == 1) {
				rdoStarter.setChecked(true);
			} else if (orderDetail.getDish().getType() == 2) {
				rdoDessert.setChecked(true);
			}

			for (Comment comment : lstComments) {
				CheckBox ch = new CheckBox(view.getContext());
				// Verifica si tiene que volver a poner los check o es la
				// primera vez que se abre la ventana
				if (check == 1) {

					for (OrderDetail od : lstDetails) {
						// Agrego el comentario abajo si existe
						if (od.getComment() != null
								&& od.getId() == FullscreenActivity.idDetail) {
							etComment.setText(od.getComment());
						}

						// Hago check en los commentarios
						if (od.getComments() != null
								&& od.getId() == FullscreenActivity.idDetail) {

							for (Comment c : od.getComments()) {
								if (c != null && comment.getId() == c.getId()) {
									ch.setChecked(true);
									intList.add(c.getId());
									//
									// tvCommentsList.setText(tvCommentsList.getText()
									// .toString() + c.getDescription());
								}
							}
						}
					}
				}
				ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						Log.i("onCheckedChanged", "=========================");
						Log.i("buttonView.getId()",
								Integer.toString(buttonView.getId()));
						if (isChecked) {
							intList.add(buttonView.getId());
						} else {
							// C�digo original - Error: Indice fuera de rango
							// Invalid index 2, size is 2
							// intList.remove(buttonView.getId());
							// ----------------------------------------
							for (int i = 0; i < intList.size(); i++)
								if (intList.get(i) == buttonView.getId()) {
									intList.remove(i);
								}
						}
					}
				});

				ch.setTextAppearance(view.getContext(), R.style.AppTitlesPopUp);
				ch.setText(comment.getDescription());
				ch.setId(comment.getId());
				ln.addView(ch);
			}

			lh.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT));
			lh.setWeightSum(2);

			LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) lh
					.getLayoutParams(); // or create new LayoutParams...

			lParams.weight = 1f;

			btnAceptar.setLayoutParams(lParams);
			btnCancelar.setLayoutParams(lParams);

			lh.addView(btnAceptar);
			lh.addView(btnCancelar);

			ln.addView(lh);

			// if (lstComments.size() == 0) {
			// FullscreenActivity.dialog.dismiss();
			// }
		}
	}

	class ExecuteConnectRabbit extends AsyncTask<String, Void, String> {

	    private Exception exception;

	    protected String doInBackground(String... urls) {
	        try {
	        	
	    		mConsumer = new MessageConsumer(Common.IP, "MenuVirtual", "fanout", FullscreenActivity.this);
	    		mConsumer.connectToRabbitMQ();
	            return "ok";
	        } catch (Exception e) {
	            this.exception = e;
	            return null;
	        }
	    }

	    protected void onPostExecute(String result) {
	    	if (result.equals("ok") && mConsumer != null){
	    		assignHandler();
	    	}
	    }
	}
	
	private void assignHandler(){
		mConsumer.setOnReceiveMessageHandler(new OnReceiveMessageHandler() {

			public void onReceiveMessage(byte[] message) {
				String text = "";
				try {
					text = new String(message, "UTF8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				showNotifications(text);

			}
		});
	}
	
	@SuppressLint("NewApi")
	private void showNotifications(String msg) {


			Intent intentNotification = new Intent(this, FullscreenActivity.class);
			PendingIntent pIntent = PendingIntent.getActivity(this, 0,
					intentNotification, 0);

			// build notification
			// the addAction re-use the same intent to keep the example short
			Notification n = new Notification.Builder(this)
					.setContentTitle("Orden Lista")
					.setContentText(msg)
					.setSmallIcon(R.drawable.warning)
					.setContentIntent(pIntent)
					.setAutoCancel(true)
					.setSound(
							RingtoneManager
									.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
					.addAction(0, "Ir a detalle", pIntent).build();

			notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


			notificationManager.notify(0, n);
			
		// Api 11
		// Notification noti = new Notification.Builder(this)
		// .setContentTitle("New mail from ")
		// .setContentText("")
		// .setSmallIcon(R.drawable.cupcake01)
		// .setLargeIcon(R.drawable.cupcake01)
		// .build();
	}
	
}
